import 'dart:async';
import 'package:flutter/material.dart';
import '../utils/app_utils.dart';

/// 全局提醒服务
class ReminderService {
  static final ReminderService _instance = ReminderService._internal();
  factory ReminderService() => _instance;
  ReminderService._internal();

  Timer? _reminderTimer;
  BuildContext? _context;

  /// 设置全局上下文
  void setContext(BuildContext context) {
    _context = context;
  }

  /// 设置提醒
  void scheduleReminder(TimeOfDay reminderTime) {
    // 取消之前的提醒
    cancelReminder();

    final now = DateTime.now();
    final reminderDateTime = DateTime(
      now.year,
      now.month,
      now.day,
      reminderTime.hour,
      reminderTime.minute,
    );

    // 如果设置的时间已经过了，则设置为明天的这个时间
    final targetDateTime = reminderDateTime.isBefore(now)
        ? reminderDateTime.add(const Duration(days: 1))
        : reminderDateTime;

    final duration = targetDateTime.difference(now);

    // 设置定时器
    _reminderTimer = Timer(duration, () {
      _showPracticeReminder();
    });

    debugPrint('Reminder scheduled for: ${targetDateTime.toString()}');
    debugPrint('Duration until reminder: ${duration.toString()}');
  }

  /// 取消提醒
  void cancelReminder() {
    _reminderTimer?.cancel();
    _reminderTimer = null;
  }

  /// 显示练习提醒
  void _showPracticeReminder() {
    if (_context != null && _context!.mounted) {
      AppUtils.showConfirmDialog(
        _context!,
        message: 'It\'s time for your guitar practice! Ready to start?',
        title: '🎸 Practice Reminder',
        confirmText: 'Start Practice',
        cancelText: 'Snooze 10min',
        onConfirm: () {
          // 可以导航到练习页面或执行其他操作
          _navigateToPracticePage();
        },
        onCancel: () {
          // 用户选择延迟10分钟
          _snoozeReminder();
        },
      );
    }
  }

  /// 延迟提醒10分钟
  void _snoozeReminder() {
    final snoozeTime = TimeOfDay(
      hour: DateTime.now().add(const Duration(minutes: 10)).hour,
      minute: DateTime.now().add(const Duration(minutes: 10)).minute,
    );
    scheduleReminder(snoozeTime);
    
    if (_context != null) {
      AppUtils.showSuccess(
        _context!,
        'Reminder snoozed for 10 minutes',
        title: 'Snoozed',
      );
    }
  }

  /// 导航到练习页面
  void _navigateToPracticePage() {
    if (_context != null) {
      // 这里可以添加导航逻辑
      // 例如：Navigator.of(_context!).pushNamed('/practice');
      
      // 暂时显示成功消息
      AppUtils.showSuccess(
        _context!,
        'Let\'s start practicing!',
        title: 'Great!',
      );
    }
  }

  /// 检查是否有活跃的提醒
  bool get hasActiveReminder => _reminderTimer != null && _reminderTimer!.isActive;

  /// 获取下次提醒时间（如果有的话）
  DateTime? get nextReminderTime {
    // 这里可以根据需要实现获取下次提醒时间的逻辑
    return null;
  }

  /// 销毁服务
  void dispose() {
    cancelReminder();
    _context = null;
  }
}
